Method of conversion between Byte [] and String in C

  • 2021-11-02 02:04:44
  • OfStack

This article shows you how to convert between Byte [] and String.

Bits (b): Bits have only 0 1, 1 for pulses and 0 for no pulses. It is the most basic unit of computer physical memory storage.

Byte (B): 8 bits, integer representation of 0-255

Encoding: Characters must be encoded before they can be processed by computer. In the early days, GB2312 and big5 were designed to deal with Chinese characters by using 7 as AscII code

The conversion between string and byte array is actually the conversion between real world information and digital world information, which inevitably involves some coding methods, and different coding methods will lead to different conversion results. System. Text. Encoding is commonly used in C # to manage common encoding. The following code is directly listed:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ByteToString
{
class Program
{
static void Main(string[] args)
{
string str = " Brother Ju is so handsome! ";
// Use UTF Coding. . . 
Byte[] utf8 = StrToByte(str, Encoding.UTF8);
// Estimate C# At that time, there was no simplified Chinese design, which was later made in China? 
Byte[] gb2312 = StrToByte(str,Encoding.GetEncoding("GB2312"));
Console.WriteLine(" This is UTF8( Brother Ju is so handsome ), The length is :{0}",utf8.Length);
foreach (var item in utf8)
{
Console.Write(item);
}
Console.WriteLine("\n\n This is gb2312( Brother Ju is so handsome ), The length is :{0}",gb2312.Length);
foreach (var item in gb2312)
{
Console.Write(item);
}
// Use utf8 Encoded byte array is converted to str
string utf8Str = ByteToStr(utf8,Encoding.UTF8);
string gb2312Str = ByteToStr(gb2312,Encoding.GetEncoding("GB2312"));
Console.WriteLine("\n\nutf8: {0}",utf8Str);
Console.WriteLine("gb2312: {0}",gb2312Str);
Console.ReadKey();
}
//C# Usually used System.Text.Encoding Code 
// String to array 
static Byte[] StrToByte(string str, Encoding encoding)
{
return encoding.GetBytes(str);
}
// Array conversion string 
static String ByteToStr(Byte[] bt,Encoding encoding)
{
return encoding.GetString(bt);
}
}
}

Related articles: